﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using Microsoft.ApplicationBlocks.Data;

namespace WSCompress
{
    /// <summary>
    /// Summary description for DataService
    /// </summary>
    [WebService(Namespace = "http://blog.wmdev.net/wscompresscf/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class DataService : System.Web.Services.WebService
    {
        private string connectionString = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;

        [WebMethod]
        [CompressionSoapExtension]
        public DataSet CheckOutCustomers()
        {
            DataSet ds = new DataSet();
            using(SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                ds = SqlHelper.ExecuteDataset(cn, CommandType.Text, "SELECT * FROM Customers", "Customers");
            }
            return ds;
        }

        [WebMethod]
        [CompressionSoapExtension]
        public void CheckInCustomers(DataSet clientDataSet)
        {
            using(SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                DataSet serverDataSet = SqlHelper.ExecuteDataset(cn, CommandType.Text, "SELECT * FROM Customers", "Customers");
                foreach(DataRow dr in clientDataSet.Tables["Customers"].Rows)
                {
                    DataRow[] drs = serverDataSet.Tables["Customers"].Select("CustomerID='" + dr["CustomerID"].ToString() + "'");
                    if(drs.Length > 0) // Update
                        for(int i = 0; i < dr.ItemArray.Length; i++)
                            drs[0][i] = dr[i];
                    else // Insert
                        serverDataSet.Tables["Customers"].Rows.Add(dr.ItemArray);
                } // Delete
                foreach(DataRow dr in serverDataSet.Tables["Customers"].Rows)
                    if(clientDataSet.Tables["Customers"].Select("CustomerID='" + dr["CustomerID"].ToString() + "'").Length < 1)
                        dr.Delete();
                SqlHelper.UpdateDataset(cn, serverDataSet, "Customers");
            }
        }
    }
}
